import { PlusOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Select, Switch, Transfer, Card } from 'antd';
import type { TransferDirection } from 'antd/es/transfer';
import React, { useEffect, useReducer, useRef, useState } from 'react';
import { history, useAccess, useLocation, useModel } from 'umi';

import {
  GetTables,
  syncColumns,
  getColumns,
  genConfig,
  gen,
  updateConfig,
} from '@/services/systemUtil/codeUtil';
import {
  DrawerForm,
  LightFilter,
  LoginForm,
  ModalForm,
  ProFormSwitch,
  ProForm,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  QueryFilter,
  StepsForm,
} from '@ant-design/pro-components';

const { Option } = Select;

// Usage of DebounceSelect

const tableConfig: React.FC<{}> = () => {
  // 表单弹框信息
  const location = useLocation();
  // 绑定角色信息弹框
  console.log(location.query.tableName, '---ceshi1---');

  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();

  // 表格数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);

  // 绑定客户信息

  // const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
  //   console.log('sourceSelectedKeys:', sourceSelectedKeys);
  //   console.log('targetSelectedKeys:', targetSelectedKeys);
  //   setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  // };

  useEffect(() => {
    // Using an IIFE
    // debugger;
    (async () => {
      // 相当于新建
      if (location.query.tableName !== undefined && location.query.tableName !== null) {
        const result = await getColumns(location.query.tableName);
        setDataSource(result?.data?.content);
      }
    })();
  }, []);

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '字段名称', //表头显示的名称
      dataIndex: 'columnName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '字段类型', //表头显示的名称
      dataIndex: 'columnType',
    },

    // {
    //   title: '客户名称', //表头显示的名称
    //   hideInTable: true,
    //   dataIndex: 'customerName',
    // },
    // {
    //   title: '昵称', //表头显示的名称
    //   search: false,
    //   dataIndex: 'nickName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    // },
    {
      title: '字段描述', //表头显示的名称
      search: false,
      dataIndex: 'remark', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
        <EditableProTable.RecordCreator
          key="copy"
          record={{
            ...record,
            id: (Math.random() * 1000000).toFixed(0),
          }}
        >
          <a>复制</a>
        </EditableProTable.RecordCreator>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard title="字段配置" bordered={false} extra={location.query.tableName}>
        <EditableProTable<TableFormDateType>
          value={dataSource}
          editableFormRef={editorFormRef}
          toolBarRender={(action, { selectedRows }) => {
            const array = [];
            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={async () => {
                  const tables = [];
                  tables.push(location.query.tableName);
                  await syncColumns(tables);
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  // SetShowUploadFile(true);
                }}
                type="primary"
              >
                代码同步
              </Button>,
            );
            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  // downloadTemplateByName({ fileName: '电机上传模板.xlsx' }).then((res) => {
                  //   const aLink = document.createElement('a');
                  //   document.body.appendChild(aLink);
                  //   aLink.style.display = 'none';
                  //   aLink.href = window.URL.createObjectURL(res);
                  //   aLink.setAttribute('download', `电机上传模板.xlsx`);
                  //   aLink.click();
                  //   document.body.removeChild(aLink);
                  // });
                }}
                type="primary"
              >
                保存
              </Button>,
            );

            array.push(
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={async () => {
                  await gen({
                    tableName: location.query.tableName,
                    type: 0,
                  });
                  // console.log(selectedRows, '---选取多行----');
                  // 1.清空form
                  // downloadTemplateByName({ fileName: '电机上传模板.xlsx' }).then((res) => {
                  //   const aLink = document.createElement('a');
                  //   document.body.appendChild(aLink);
                  //   aLink.style.display = 'none';
                  //   aLink.href = window.URL.createObjectURL(res);
                  //   aLink.setAttribute('download', `电机上传模板.xlsx`);
                  //   aLink.click();
                  //   document.body.removeChild(aLink);
                  // });
                }}
                type="primary"
              >
                生成
              </Button>,
            );
            return array;
          }}
          // editable={{
          //   type: 'multiple',
          //   onChange: (rowKey, row) => {
          //     console.log(rowKey, row, '--rowKey---');
          //   },
          // }}
          recordCreatorProps={{
            record: () => {
              return {
                id: `0${Date.now()}`,
                // controlMode: 1,
                // commTelegram: 105,
                // controlMode: { value: 1, label: 'TO' },
                // commTelegram: { value: 105, label: '105' },
              };
            },
          }}
          // request={async () => ({
          //   data: defaultData,
          //   total: 3,
          //   success: true,
          // })}
          onChange={setDataSource}
          columns={columns}
          rowKey="id"
        />
      </ProCard>
      <ProCard
        title="生成配置"
        bordered={false}
        extra={location.query.tableName}
        style={{ marginBlockStart: 8 }}
      >
        <ProForm
          // onValuesChange={(changeValues) => console.log(changeValues)}
          layout="horizontal"
          onFinish={async (values) => {
            await updateConfig({ ...values, tableName: location.query.tableName });
            console.log(values);
          }}
          request={async () => {
            const result = await genConfig(location.query.tableName);

            if (result?.data == null) {
              return {};
            } else {
              return result?.data;
            }

            // return {
            //   name: '蚂蚁设计有限公司',
            //   useMode: 'chapter',
            // };
          }}
        >
          <ProFormText width="md" name="id" label="作者名称" hidden={true} />
          <ProFormText width="md" name="author" label="作者名称" />
          <ProFormText width="md" name="moduleName" label="模块名称" />
          <ProFormText width="md" name="pack" label="至于包下" />
          <ProFormText width="md" name="apiAlias" label="接口前缀" />
          <ProFormText width="md" name="path" label="前端路径" />
          <ProFormText width="md" name="prefix" label="去表前缀" />
          <ProFormSwitch initialValue={false} label="是否覆盖" name="grid" />
        </ProForm>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default tableConfig;
